package com.fuze.controller;

import com.fuze.common.Advice;
import com.fuze.common.CustomException;
import com.fuze.common.Result;
import com.fuze.common.constant.Constant;
import com.fuze.service.UploadService;
import com.fuze.utils.CheckFileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.Stream;

/**
 * @author sepc_
 * @date 4/20/2021 14:13
 */
@Api(tags = "文件上传接口")
@Slf4j
@RequiredArgsConstructor
@RestController
public class UploadController {


    final
    HttpServletRequest request;
    final
    UploadService uploadService;

    /**
     * 图片上传接口
     *
     * @param imageList 上传的图片列表
     * @return 统一返回结果
     */
    @ApiOperation(value = "图片上传接口")
    @PostMapping(value = "/image/upload",consumes = "multipart/form-data")
    public Result imageUpload(@NotNull(message = "上传图片数据不能为空") MultipartFile[] imageList) {
        Stream.of(imageList)
                .forEach(image -> {
                    String suffix = CheckFileUtils.getSuffix(image).orElseThrow(() -> new CustomException(Advice.FAILED_IMAGE_UPLOAD));
                    if (suffix.matches(Constant.SUFFIX_IMAGE_REG)) {
                        throw new CustomException(Advice.FAILED_VERIFICATION);
                    }
                    String header;
                    try {
                        InputStream is = image.getInputStream();
                        header = CheckFileUtils.getFileHeader(is);
                        boolean checked = CheckFileUtils.check(header);
                        if (!checked) {
                            throw new CustomException(Advice.FAILED_VERIFICATION);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error("校验图片读取失败！，失败原因：{}", e.getMessage(), e);
                    }
                });
        return Result.ok(uploadService.upload(imageList));
    }


    /**
     * todo:图片的下载功能，是否需要
     */
    @ApiIgnore
    @GetMapping()
    public Result downloadImage() {
        return Result.ok();
    }


}
